/**
 * 
 */
package com.ap.core.business.message.transaction.service.impl;

import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.ap.core.business.message.transaction.service.APTransactionGenerationService;
import com.ap.core.domain.sequence.generation.MultiIdGenerationService;
import com.ap.core.transaction.APTransactionChecksumHelper;
import com.ap.core.transaction.APTransactionGeneratorUtil;
import com.ap.core.transaction.APTransactionInfo;

/**
 * The Implementation Class for AP Transaction Generation Service.
 *
 * @author Dilip.Sridhar
 */
public class APTransactionGenerationServiceImpl implements 	APTransactionGenerationService {
	

	/** The Constant AP_TRANSACTION_ID. */
	private static final String AP_TRANSACTION_ID = "AP_TRANSACTION_ID";

	private static final String yyMMdd_Format = "yyMMdd";
	
	private static final String ZERO = "0";
	
	/** The MultiId generation service. */
	private MultiIdGenerationService<Long> multiIdGenerationService;	
	
	/* (non-Javadoc)
	 * @see com.ap.core.business.message.transaction.service.APTransactionGenerationService#generateApTransaction()
	 */
	@Override
	public APTransactionInfo generateApTransaction(LocalDate reconciliationLocalDate) {
			final DateTimeFormatter yyMMddFORMAT = DateTimeFormat.forPattern(yyMMdd_Format);
	        final String dateString = reconciliationLocalDate.toString( yyMMddFORMAT );
    		final StringBuilder apTxnRetrievalIdBuilder = new StringBuilder(dateString);
    		final Long sequenceNumber = multiIdGenerationService.getNextId(AP_TRANSACTION_ID);
	        final String sequenceNumberStr = StringUtils.leftPad(String.valueOf(sequenceNumber),11,ZERO);
	        final int checksumDigit = APTransactionChecksumHelper.generateChecksumForSequence(sequenceNumber);
	        final String sequenceNumberWithChecksum = sequenceNumberStr + checksumDigit;
	        final String apTxnRetrievalId = apTxnRetrievalIdBuilder.append(sequenceNumberWithChecksum).toString();
	        final String apTransactionId = APTransactionGeneratorUtil.generateBase36EncodedAPTransactionId(apTxnRetrievalId);	        
	        
		return new APTransactionInfo(apTransactionId, apTxnRetrievalId);
	}	
	
	
	/**
	 * Sets the multi id generation service.
	 *
	 * @param multiIdGenerationService the new multi id generation service
	 */
	public void setMultiIdGenerationService(MultiIdGenerationService<Long> multiIdGenerationService) {
        this.multiIdGenerationService = multiIdGenerationService;
    }


}
